package com.akeil.flash.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.akeil.flash.config.EDeviceType;
import com.akeil.flash.config.IConstantsConfig;
import com.akeil.flash.dialog.LimisInfoDialog;
import com.akeil.flash.dialog.LimisInfoOpenDialog;
import com.akeil.flash.pojo.Data;
import com.akeil.flash.preferences.IPreferenceConstants;
import com.akeil.flash.utils.LimsXMLMaker;

import flash.Activator;

public class OutputLimsAction extends AbstractFlashAction {
	// TODO Auto-generated method stub
	IPreferenceStore store = Activator.getDefault().getPreferenceStore();
			/* Serial port Default setting */
	private List<Data> datas = new ArrayList<Data>();
	private int count = 0;
	private TableViewer tableViewer = null;
	private Table tableData = null;
	
	public OutputLimsAction(TableViewer tableViewer) {
		this.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
				Activator.PLUGIN_ID, "icons/view/XML_16px.png"));
		this.setToolTipText("输出试验Limis报告");
		this.setText("Limis");
		this.tableViewer = tableViewer;
		this.tableData = tableViewer.getTable();
	}

	@Override
	public void run() {
		//getData();
		String xmlFileName =  "report.xml";
		if(datas != null && datas.size() > 0){
			xmlFileName = datas.get(0).getSamplename() + "-" + datas.get(0).getSampleno() + "-" + datas.get(0).getTesttime() + ".xml";
			xmlFileName = xmlFileName.replace(":", "-");
		}else{
			xmlFileName = "report.xml";
		}
		
		String pathname = store.getString(IPreferenceConstants.DIRECTORY_OUTPUT_XML);
		int methodno = store.getInt(IPreferenceConstants.LIMS_METHOD);
		String username = store.getString(IPreferenceConstants.LIMS_USERNAME);
		String password = store.getString(IPreferenceConstants.LIMS_PASSWORD);
		
		
		if(getCheckedData()){
			if(IConstantsConfig.deviceType == EDeviceType.MANUAL){
				processClose(pathname,xmlFileName,methodno,username,password);
			}else{
				processOpen(pathname,xmlFileName,methodno,username,password);
			}
		}	
	}
	
	private boolean getData(){
		TableItem[] selections = tableData.getSelection();
		datas.clear();
		if (selections.length > 0) {
			for (TableItem tableItem : selections) {
				boolean checked = tableItem.getChecked();
				Data exdata = (Data) tableItem.getData();				
				datas.add(exdata);
			}

		} else {
			Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
			MessageDialog.openInformation(parentShell,"提示","请选择要输出的数据！");
			return false;
		}
		return true;
	}
	
	private boolean getCheckedData(){
		TableItem[] selections = tableData.getItems();
		datas.clear();
		for (TableItem tableItem : selections) {
			boolean checked = tableItem.getChecked();
			if(checked){
				Data exdata = (Data) tableItem.getData();				
				datas.add(exdata);
			}				
		}
		
		if (datas.size() == 0) {
			Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
			MessageDialog.openInformation(parentShell,"提示","请选择要输出的数据！");
			return false;
		}
		
		return true;
	}

	private void processClose(String pathname,String xmlFileName,int methodno,String username,String password){
		Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		LimisInfoDialog limisInfoDialog = new LimisInfoDialog(parentShell,pathname + File.separator + xmlFileName);
		Data theData = datas.get(0);
		limisInfoDialog.setSampleNo(theData.getSampleno());
		limisInfoDialog.setMethodno(methodno);
		limisInfoDialog.setUsername(username);
		limisInfoDialog.setPassword(password);
		if(IDialogConstants.OK_ID == limisInfoDialog.open()){
			if(limisInfoDialog.getMethodno() > 0 && datas.size() <= 1){
				MessageDialog.openInformation(parentShell, "提示", "该分析方法需要选择两组试验结果！请从新选择！");
				return;
			}
			
			LimsXMLMaker limsXMLMaker = new LimsXMLMaker();
			limsXMLMaker.setUsername(limisInfoDialog.getUsername());
			limsXMLMaker.setPassword(limisInfoDialog.getPassword());
			limsXMLMaker.setSampleno(limisInfoDialog.getSampleNo());
			limsXMLMaker.setAnasysisMethod(limisInfoDialog.getMethod());
			limsXMLMaker.setMethodNo(limisInfoDialog.getMethodno());
			limsXMLMaker.setNote(limisInfoDialog.getNote() == null ? "" : limisInfoDialog.getNote());
			limsXMLMaker.setFullFileName(limisInfoDialog.getNewFilename());
			count = 1;
			
			methodno = limisInfoDialog.getMethodno();
			store.putValue(IPreferenceConstants.LIMS_METHOD, String.valueOf(methodno));
			
			if(methodno == 0){// 方法0
				try {
			       	 IRunnableWithProgress runnable = new IRunnableWithProgress() {
			                   public void run(IProgressMonitor monitor) {
			                       monitor.beginTask("开始执行LIMS文档输出......", datas.size());
								
			                       for (Data data : datas) {
				           				String xmlFileName = data.getSamplename() + "-" + data.getSampleno() + "-" + data.getTesttime() + ".xml";
				           				xmlFileName = xmlFileName.replace(":", "-");
				           				if(limisInfoDialog.getOldFilename().equals(limisInfoDialog.getNewFilename())){
				           					limsXMLMaker.setFullFileName(pathname + File.separator + xmlFileName);
				           				}
				           				
				           				limsXMLMaker.outputLIMS(data);
				           				try {
											Thread.sleep(100);
										} catch (InterruptedException e) {
											// TODO 自动生成的 catch 块
											e.printStackTrace();
										}
				           				monitor.setTaskName("共有 " +  datas.size() + " 个文档，正在输出第 " + count + " 个文档，请稍等......");
				           				count++;
				           				monitor.worked(1);
			           			   }
			                       monitor.done();// 进度条前进到完成
			                   }
			               };
			               try {
			                   // 创建一个进度条对话框，并将runnable传入
			                   // 第一个参数推荐设为true，如果设为false则处理程序会运行在UI线程里，界面将有一点停滞感。
			                   // 第二个参数：true＝对话框的“取消”按钮有效
			                   new ProgressMonitorDialog(parentShell).run(true, true, runnable);
			               } catch (Exception e2) {
			                   e2.printStackTrace();
			               }
						
			               MessageDialog.openInformation(parentShell, "信息", "文件输出成功，共输出 " + datas.size() + " 个文档。");
					}catch(Exception e){
						e.printStackTrace();
					}
			}else{// 方法1,2,3
				try {
			       	 IRunnableWithProgress runnable = new IRunnableWithProgress() {
			                   public void run(IProgressMonitor monitor) {
			                       monitor.beginTask("开始执行LIMS文档输出......", datas.size() / 2);
								
			                       for (int i = 0 ; i < datas.size() / 2; i++) {
			                    	    Data data1 = datas.get(2 * i);
			                    	    Data data2 = datas.get(2 * i + 1);
			                    	   
				           				String xmlFileName = data1.getSamplename() + "-" + data1.getSampleno() + "-" + data1.getTesttime() + ".xml";
				           				xmlFileName = xmlFileName.replace(":", "-");
				           				if(limisInfoDialog.getOldFilename().equals(limisInfoDialog.getNewFilename())){
				           					limsXMLMaker.setFullFileName(pathname + File.separator + xmlFileName);
				           				}
				           				limsXMLMaker.outputLIMS(data1,data2);
				           				try {
											Thread.sleep(100);
										} catch (InterruptedException e) {
											// TODO 自动生成的 catch 块
											e.printStackTrace();
										}
				           				monitor.setTaskName("共有 " +  datas.size() / 2 + " 个文档，正在输出第 " + count + " 个文档，请稍等......");
				           				count++;
				           				monitor.worked(1);
			           			   }
			                       monitor.done();// 进度条前进到完成
			                   }
			               };
			               try {
			                   // 创建一个进度条对话框，并将runnable传入
			                   // 第一个参数推荐设为true，如果设为false则处理程序会运行在UI线程里，界面将有一点停滞感。
			                   // 第二个参数：true＝对话框的“取消”按钮有效
			                   new ProgressMonitorDialog(parentShell).run(true, true, runnable);
			               } catch (Exception e2) {
			                   e2.printStackTrace();
			               }
						
			               MessageDialog.openInformation(parentShell, "信息", "文件输出成功，共输出 " + datas.size() / 2 + " 个文档。");
					}catch(Exception e){
						e.printStackTrace();
					}
			}
			
		}
	}
	
	
	private void processOpen(String pathname,String xmlFileName,int methodno,String username,String password){
		Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		LimisInfoOpenDialog limisInfoDialog = new LimisInfoOpenDialog(parentShell,pathname + File.separator + xmlFileName);
		Data theData = datas.get(0);
		limisInfoDialog.setSampleNo(theData.getSampleno());
		limisInfoDialog.setMethodno(methodno);
		limisInfoDialog.setUsername(username);
		limisInfoDialog.setPassword(password);
		if(IDialogConstants.OK_ID == limisInfoDialog.open()){
			if(limisInfoDialog.getMethodno() > 0 && datas.size() <= 1){
				MessageDialog.openInformation(parentShell, "提示", "该分析方法需要选择两组试验结果！请从新选择！");
				return;
			}
			
			LimsXMLMaker limsXMLMaker = new LimsXMLMaker();
			limsXMLMaker.setUsername(limisInfoDialog.getUsername());
			limsXMLMaker.setPassword(limisInfoDialog.getPassword());
			limsXMLMaker.setSampleno(limisInfoDialog.getSampleNo());
			limsXMLMaker.setAnasysisMethod(limisInfoDialog.getMethod());
			limsXMLMaker.setMethodNo(limisInfoDialog.getMethodno());
			limsXMLMaker.setNote(limisInfoDialog.getNote() == null ? "" : limisInfoDialog.getNote());
			limsXMLMaker.setFullFileName(limisInfoDialog.getNewFilename());
			count = 1;
			
			methodno = limisInfoDialog.getMethodno();
			store.putValue(IPreferenceConstants.LIMS_METHOD, String.valueOf(methodno));
			
			if(methodno == 0){// 方法0
				try {
			       	 IRunnableWithProgress runnable = new IRunnableWithProgress() {
			                   public void run(IProgressMonitor monitor) {
			                       monitor.beginTask("开始执行LIMS文档输出......", datas.size());
								
			                       for (Data data : datas) {
				           				String xmlFileName = data.getSamplename() + "-" + data.getSampleno() + "-" + data.getTesttime() + ".xml";
				           				xmlFileName = xmlFileName.replace(":", "-");
				           				if(limisInfoDialog.getOldFilename().equals(limisInfoDialog.getNewFilename())){
				           					limsXMLMaker.setFullFileName(pathname + File.separator + xmlFileName);
				           				}
				           				
				           				limsXMLMaker.outputLIMS(data);
				           				try {
											Thread.sleep(100);
										} catch (InterruptedException e) {
											// TODO 自动生成的 catch 块
											e.printStackTrace();
										}
				           				monitor.setTaskName("共有 " +  datas.size() + " 个文档，正在输出第 " + count + " 个文档，请稍等......");
				           				count++;
				           				monitor.worked(1);
			           			   }
			                       monitor.done();// 进度条前进到完成
			                   }
			               };
			               try {
			                   // 创建一个进度条对话框，并将runnable传入
			                   // 第一个参数推荐设为true，如果设为false则处理程序会运行在UI线程里，界面将有一点停滞感。
			                   // 第二个参数：true＝对话框的“取消”按钮有效
			                   new ProgressMonitorDialog(parentShell).run(true, true, runnable);
			               } catch (Exception e2) {
			                   e2.printStackTrace();
			               }
						
			               MessageDialog.openInformation(parentShell, "信息", "文件输出成功，共输出 " + datas.size() + " 个文档。");
					}catch(Exception e){
						e.printStackTrace();
					}
			}else{// 方法1,2,3
				try {
			       	 IRunnableWithProgress runnable = new IRunnableWithProgress() {
			                   public void run(IProgressMonitor monitor) {
			                       monitor.beginTask("开始执行LIMS文档输出......", datas.size() / 2);
								
			                       for (int i = 0 ; i < datas.size() / 2; i++) {
			                    	    Data data1 = datas.get(2 * i);
			                    	    Data data2 = datas.get(2 * i + 1);
			                    	   
				           				String xmlFileName = data1.getSamplename() + "-" + data1.getSampleno() + "-" + data1.getTesttime() + ".xml";
				           				xmlFileName = xmlFileName.replace(":", "-");
				           				if(limisInfoDialog.getOldFilename().equals(limisInfoDialog.getNewFilename())){
				           					limsXMLMaker.setFullFileName(pathname + File.separator + xmlFileName);
				           				}
				           				limsXMLMaker.outputLIMS(data1,data2);
				           				try {
											Thread.sleep(100);
										} catch (InterruptedException e) {
											// TODO 自动生成的 catch 块
											e.printStackTrace();
										}
				           				monitor.setTaskName("共有 " +  datas.size() / 2 + " 个文档，正在输出第 " + count + " 个文档，请稍等......");
				           				count++;
				           				monitor.worked(1);
			           			   }
			                       monitor.done();// 进度条前进到完成
			                   }
			               };
			               try {
			                   // 创建一个进度条对话框，并将runnable传入
			                   // 第一个参数推荐设为true，如果设为false则处理程序会运行在UI线程里，界面将有一点停滞感。
			                   // 第二个参数：true＝对话框的“取消”按钮有效
			                   new ProgressMonitorDialog(parentShell).run(true, true, runnable);
			               } catch (Exception e2) {
			                   e2.printStackTrace();
			               }
						
			               MessageDialog.openInformation(parentShell, "信息", "文件输出成功，共输出 " + datas.size() / 2 + " 个文档。");
					}catch(Exception e){
						e.printStackTrace();
					}
			}
			
		}
	}
}
